import store from "@/store";
/**
 * 通用js方法封装处理
 * Copyright (c) 2023 Cauli
 */

const defaultTitle = "Cauli网盘";

// 表单重置
export function resetForm(refName) {
  if (this.$refs[refName]) {
    this.$refs[refName].resetFields();
  }
}

// 动态修改标题
export function useDynamicTitle() {
  if (store.state.settings.dynamicTitle) {
    document.title = `${store.state.settings.title} - ${defaultTitle}`;
  } else {
    document.title = defaultTitle;
  }
}

// 转换字符串，undefined,null等转化为""
export function parseStrEmpty(str) {
  if (!str || str === "undefined" || str === "null" || str === null) {
    return "";
  }
  return str;
}

// 添加时间查询参数
export function addTimeRange(params, dateRange) {
  if (dateRange != null) {
    const [beginTime, endTime] = dateRange;
    params.beginTime = beginTime;
    params.endTime = endTime;
  } else {
    params.beginTime = null;
    params.endTime = null;
  }
  return params;
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(data, id, parentId, children) {
  const config = {
    id: id || "id",
    parentId: parentId || "parentId",
    childrenList: children || "children",
  };

  const childrenListMap = {};
  const nodeIds = {};
  const tree = [];

  for (const d of data) {
    const parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[parentId].push(d);
  }

  for (const d of data) {
    const parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      tree.push(d);
    }
  }

  for (const t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      for (const c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
  }

  return tree;
}

// 返回项目路径
export function getNormalPath(p) {
  if (p.length === 0 || !p) {
    return p;
  }
  const res = p.replace("//", "/");
  if (res[res.length - 1] === "/") {
    return res.slice(0, res.length - 1);
  }
  return res;
}
